package com.itheima.code.strategy;

import org.cent.scanner.core.scanner.ClassScanner;
import org.cent.scanner.core.scanner.impl.DefaultClassScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HandlerProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        Map<String,Class> handlerMap = new HashMap<>();
        List<String> scanPkgs = Arrays.asList(
                "com.itheima.code.strategy.impl"
        );
        ClassScanner classScanner = new DefaultClassScanner();
        //扫描包下包含有 @HandlerType的所有类
        List<Class> scan = classScanner.scan(scanPkgs);

        classScanner.scan(scanPkgs).forEach(clazz->{
            HandlerType annotation = (HandlerType) clazz.getAnnotation(HandlerType.class);
            if (annotation != null){
                String value = annotation.value();
                handlerMap.put(value,clazz);
            }
        });

        //
        HandlerContext1 context = new HandlerContext1(handlerMap);
        //创建的对象存储在IOC容器中，单例的
        beanFactory.registerSingleton(HandlerContext1.class.getName(),context);
    }
}
